package com.beiding.workordersystem.resource.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.beiding.workordersystem.common.service.BaseService;
import com.beiding.workordersystem.common.standard.E;
import com.beiding.workordersystem.common.utils.MySecurityUtils;
import com.beiding.workordersystem.common.utils.QueryUtils;
import com.beiding.workordersystem.resource.dao.ResourceDao;
import com.beiding.workordersystem.resource.entity.Resource;
import com.beiding.workordersystem.resource.service.ResourceService;
import com.beiding.workordersystem.system.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ResourceServiceImpl extends BaseService implements ResourceService {

    @Autowired
    private ResourceDao resourceDao;

    @Autowired
    private UserService userService;


    @Override
    public IPage<Resource> page(IPage page, Resource resource, Boolean my, Boolean audit) {
        LambdaQueryWrapper<Resource> query = QueryUtils.getQuery(resource);

        //非主存

        if (my) {
            query.eq(Resource::getTakeUserId, MySecurityUtils.currentCredentials().getUserId());
            query.isNotNull(Resource::getMainId);
        } else {
            query.isNull(Resource::getMainId);
        }

        if (audit) {
            //不显示已出库和正在使用中的
            query.ne(Resource::getStatus, 6).ne(Resource::getStatus, 4);
        }

        if (notEmpty(resource.getName())) {
            query.like(Resource::getName, resource.getName());
        }

        IPage<Resource> iPage = resourceDao.selectPage(page, query);

        if (iPage.getRecords().size() > 0) {
            if (my) {
                for (Resource record : iPage.getRecords()) {
                    record.setHasChildren(false);
                }
            } else {
                for (Resource record : iPage.getRecords()) {
                    record.setChildren(loadChildren(record.getId()));
                    if (record.getChildren().size() > 0) {
                        record.setHasChildren(true);
                    } else {
                        record.setHasChildren(false);
                    }
                }
            }
        }

        return iPage;
    }

    //保存后就直接交给审核员进行审核
    @Override
    @Transactional
    public void save(Resource resource) {
        resource.setSaveUserId(MySecurityUtils.currentCredentials().getUserId());
        if (fillId(resource)) {
            resource.setStatus(1);
            resourceDao.insert(resource);

            copy(resource);

        } else {
            Resource select = get(resource.getId());
            E.notNull(select, "被修改的资料不存在");
            E.isTrue(select.getStatus().equals(1), "当前状态不可编辑");
            resource.setErrorStatus(null);
            update(resource);
            resourceDao.delete(QueryUtils.getQuery(resource).eq(Resource::getMainId, resource.getId()));
            copy(resource);
        }
    }

    private void copy(Resource resource) {

        //创建主存衍生
        String s = resource.getResource();
        String[] split = s.split(",");
        for (String r : split) {
            Resource copy = new Resource();
            BeanUtils.copyProperties(resource, copy);
            copy.setId(createId());
            copy.setResource(r);
            copy.setMainId(resource.getId());
            resourceDao.insert(copy);
        }

    }


    @Override
    @Transactional
    public void remove(String[] ids) {
        for (String id : ids) {
            Resource resource = get(id);
/*
            List<Resource> resources = loadChildren(id);
            for (Resource r : resources) {
                E.isFalse(r.getStatus() != 2, "当前状态不可申请出库");
            }
*/

            resource.setStatus(5);
            resource.setRemoveUserId(MySecurityUtils.currentCredentials().getUserId());
            resource.setErrorStatus(null);
            update(resource);
        }
    }

    @Override
    @Transactional
    public void take(String[] ids) {
        for (String id : ids) {
            Resource resource = get(id);
            E.isTrue(resource.getStatus() == 2, "当前状态不可领用");
            resource.setTakeUserId(MySecurityUtils.currentCredentials().getUserId());
            resource.setStatus(3);
            resource.setErrorStatus(null);
            resourceDao.updateById(resource);

            //同步状态
            Resource main = get(resource.getMainId());
            main.setStatus(8);
            resourceDao.updateById(main);

        }
    }

    @Override
    public void delete(String[] ids) {
        for (String id : ids) {
            //查看是否具有资源强制删除的权限
            boolean h = MySecurityUtils.currentCredentials().hasAuthority("resource_delete");
            if (h) {
                deleteForce(id);
            } else {
                deleteSafe(id);
            }
        }

    }

    @Override
    @Transactional
    public void passSave(String[] ids) {
        for (String id : ids) {
            Resource resource = get(id);
            assertStatus(resource, 1);
            resource.setStatus(2);
            resource.setErrorStatus(null);

            resource.setSaveTime(new Date());
            update(resource);
        }
    }

    @Override
    public void refuseSave(String[] ids) {
        for (String id : ids) {
            Resource resource = get(id);
            assertStatus(resource, 1);
            resource.setErrorStatus(-1);
            update(resource);
        }
    }

    @Override
    public void passTake(String[] ids) {
        for (String id : ids) {
            Resource resource = get(id);
            assertStatus(resource, 3);
            resource.setStatus(4);
            resource.setErrorStatus(null);
            resource.setTakeTime(new Date());
            update(resource);
        }
    }

    @Override
    public void refuseTake(String[] ids) {
        for (String id : ids) {
            Resource resource = get(id);
            assertStatus(resource, 3);
            resource.setStatus(2);
            resource.setTakeUserId(null);
            update(resource);
            Resource main = get(resource.getMainId());
            main.setStatus(2);
            resourceDao.updateById(main);

        }
    }

    //通过出库请求
    @Override
    public void passRemove(String[] ids) {
        for (String id : ids) {
            Resource resource = get(id);
            assertStatus(resource, 5);
            resource.setStatus(6);
            resource.setErrorStatus(null);
            resource.setRemoveTime(new Date());
            update(resource);
        }
    }

    @Override
    public void refuseRemove(String[] ids) {
        for (String id : ids) {
            Resource resource = get(id);
            assertStatus(resource, 5);
            resource.setErrorStatus(-5);
            resource.setStatus(2);
            update(resource);
        }
    }

    @Override
    public void giveBack(String[] ids) {
        for (String id : ids) {
            Resource resource = get(id);
            assertStatus(resource, 4);
            E.isTrue(resource.getTakeUserId().equals(MySecurityUtils.currentCredentials().getUserId()), "不是你认领,无法归还");
            resource.setErrorStatus(null);
            resource.setStatus(7);
            resourceDao.updateById(resource);
        }
    }

    @Override
    public void refuseGiveBack(String[] ids) {
        for (String id : ids) {
            Resource resource = get(id);
            assertStatus(resource, 7);
            resource.setStatus(4);
            resource.setErrorStatus(-7);
            resourceDao.updateById(resource);
        }
    }

    @Override
    public void passGiveBack(String[] ids) {
        for (String id : ids) {
            Resource resource = get(id);
            assertStatus(resource, 7);
            resource.setTakeUserId(null);
            resource.setErrorStatus(null);
            resource.setTakeTime(null);
            resource.setStatus(2);
            resource.setGiveBackTime(new Date());
            resourceDao.updateById(resource);

            List<Resource> resources = loadChildren(resource.getMainId());

            boolean u = true;

            for (Resource r : resources) {
                if (r.getStatus() != 2) {
                    u = false;
                }
            }

            if (u) {
                Resource main = get(resource.getMainId());
                main.setStatus(2);
                resourceDao.updateById(main);
            }
        }
    }

    @Override
    public Resource details(String id) {
        Resource resource = resourceDao.selectById(id);
        if (resource != null) {
            if (resource.getSaveUserId() != null) {
                resource.setSaveUser(userService.getById(resource.getSaveUserId()));
            }

            if (resource.getRemoveUserId() != null) {
                resource.setRemoveUser(userService.getById(resource.getRemoveUserId()));
            }

            if (resource.getTakeUserId() != null) {
                resource.setTakeUser(userService.getById(resource.getTakeUserId()));
            }
        }
        return resource;
    }

    @Override
    public List<Resource> loadChildren(String mainId) {
        return resourceDao.selectList(QueryUtils.getQuery(Resource.class).eq(Resource::getMainId, mainId));
    }

    private void deleteSafe(String id) {
        Resource resource = get(id);
        E.isTrue(resource.getStatus().equals(6), "资料未出库不可删除");
        resourceDao.deleteById(id);
        resourceDao.delete(QueryUtils.getQuery(resource).eq(Resource::getMainId, resource.getId()));

    }

    private void deleteForce(String id) {
        Resource resource = get(id);
        E.isFalse(resource.getStatus().equals(4), "资料使用中不可删除");
        resourceDao.deleteById(id);
        resourceDao.delete(QueryUtils.getQuery(resource).eq(Resource::getMainId, resource.getId()));
    }


    private Resource get(String id) {
        Resource resource = resourceDao.selectById(id);
        E.notNull(resource, "资料不存在");
        return resource;
    }

    private void update(Resource resource) {
        resourceDao.updateById(resource);
        List<Resource> resources = loadChildren(resource.getId());
        for (Resource r : resources) {
            String id = r.getId();
            String rResource = r.getResource();
            BeanUtils.copyProperties(resource, r);
            r.setId(id);
            r.setResource(rResource);
            resourceDao.updateById(r);
        }
    }

    private void assertStatus(Resource resource, Integer status) {
        E.isTrue(resource.getStatus().equals(status), "状态错误");
    }

}
